<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="resetForm"
        @reset="searchSubmit"
      >
        <Button
          style="display: inline-block;margin-right:10px;"
          @click="handleCheck"
        >检查</Button>
        <Button
          style="display: inline-block;"
          @click="handleExport"
        >导出</Button>
        <Button
          style="display: inline-block;"
          @click="handleToXg"
        >同步数据到浒关</Button>
      </FilterForm>
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer
        style="
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="display: flex; margin: 0">
          <Button
            icon="add"
            style="margin-right: 12px"
            @click="handleAdd"
          >新增</Button>
          <Button style="display: inline-block;" @click="handleJc">继承</Button>
          <!-- <Button type="info" @click="actionUnfoldFunc(false)">继承</Button> -->
        </div>
        <!-- <div>最近一次更新时间：2021-09-22 17:55:55</div> -->
      </OperationContainer>
      <el-table
        ref="ctab"
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        row-key="code"
        height="100%"
      >
        <el-table-column align="center" type="index" label="序号" width="60" />
        <el-table-column prop="ruleCode" label="账套编码" />
        <el-table-column prop="extendField3" label="账套名称" />
        <el-table-column prop="salaryItemCode" label="工资项目编码" />
        <el-table-column prop="salaryItemName" label="工资项目名称" />
        <el-table-column prop="costItemCode" label="成本项目编码" />
        <el-table-column prop="costItemName" label="成本项目名称" />
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              style="margin-left: 10px"
            >
              <i
                class="el-icon-delete"
                style="
                  padding-top: 4px;
                  font-size: 20px;
                  color: #207efa;
                  cursor: pointer;
                "
                @click="handleDel(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      />
      <Dialog
        :title="title"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="dialogVisible = false"
        @confirm="handleConfirm"
      >
        <el-form
          ref="form"
          class="form-box"
          :model="formInfo"
          label-width="100px"
          size="small"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="年月">
                <el-date-picker
                  v-model="newYearMonth"
                  style="width:100%;"
                  type="month"
                  value-format="yyyy-MM"
                  placeholder="请选择月"
                  :picker-options="expireTimeOptionBm"
                  @change="handleYMToZt"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账套">
                <el-select
                  v-model="formInfo.ruleCode"
                  placeholder="请选择"
                  filterable
                  @change="handleChangeZt"
                >
                  <el-option
                    v-for="item in ztList"
                    :key="item.acCode"
                    :label="item.name"
                    :value="item.acCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-for="(item, index) in formInfo.domains"
            :key="index"
            class="list-item"
          >
            <el-col :span="12">
              <el-form-item :label="'工资项目' + (Number(index) + 1)">
                <el-select
                  v-model="item.salaryItemCode"
                  placeholder="请选择"
                  style="width:100%;"
                >
                  <el-option
                    v-for="item in gzList"
                    :key="item.salaItemCode"
                    :label="item.salaItemName"
                    :value="item.salaItemCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'成本项目' + (Number(index) + 1)">
                <el-select
                  v-model="item.costItemCode"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in cbList"
                    :key="index"
                    :label="item.edName"
                    :value="item.edCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <i
              v-if="index == 0"
              class="el-icon-circle-plus-outline"
              @click="handleAddFormItem"
            />
            <i
              v-else
              class="el-icon-circle-close"
              @click="handleReduceFormItem(index)"
            />
          </el-row>
        </el-form>
      </Dialog>
      <!-- 继承 -->
      <Dialog
        title="继承"
        :visible="isShowJc"
        :footer-btns="[
          {
            text: '保存',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="isShowJc = false"
        @confirm="handleSaveJc"
      >
        <el-form
          ref="formData"
          :model="formData"
          label-width="80px"
          size="small"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="源年份">
                <el-date-picker
                  v-model="formData.yearMonthOld"
                  type="month"
                  value-format="yyyy-MM"
                  format="yyyy-MM"
                  placeholder="选择日期"
                  @change="handleYmOldData"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标年份">
                <el-date-picker
                  v-model="formData.yearMonthNew"
                  type="month"
                  value-format="yyyy-MM"
                  format="yyyy-MM"
                  placeholder="选择日期"
                  @change="handleYmNewData"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="源账套">
                <el-select
                  v-model="formData.ruleCodeOld"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in ztOldData"
                    :key="item.acCode"
                    :label="item.name"
                    :value="item.acCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标账套">
                <el-select
                  v-model="formData.ruleCodeNew"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="item in ztNewData"
                    :key="item.acCode"
                    :label="item.name"
                    :value="item.acCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Dialog>
      <Drawer
        :visible="tableDialog"
        title="检查"
        :footer-btns="[
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        width="300px"
        @cancel="tableDialog = false"
      >
        <div class="jc-wraper">
          <div
            v-for="(item, index) in tableDataDialog"
            :key="index"
            class="jc-item"
          >
            <span>代码: {{ item.salaryItemCode }}</span>,
            <span>名称: {{ item.salaryItemName }}</span>
          </div>
        </div>
        <!-- <el-table
          v-loading="isDialog"
          :data="tableDataDialog"
          border
          :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
          header-row-class-name="ck-table-header"
          row-class-name="ck-table-row"
          size="mini"
          height="100%"
          style="width: 600px"
        >
          <el-table-column align="center" type="index" label="" width="60" />
          <el-table-column
            prop="ruleCode"
            label="账套Id"
            width="120"
          />
          <el-table-column prop="acSetName" label="账套名称" />
          <el-table-column
            prop="salaryItemCode"
            label="项目id"
            width="120"
          />
          <el-table-column prop="salaryItemName" label="项目名称" />
        </el-table> -->
      </Drawer>
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  getEnumDetailSource,
  rdCostsalaryrelationDown
} from '../../../utils/apis/basic'
import {
  getRdCostSalaryRelation,
  insertBatchRdCostSalaryRelation,
  batchDeleteRdCostSalaryRelation,
  modifyRdCostSalaryRelation,
  getSalarySource,
  getAcSetSource,
  inheritzt,
  checkRelation,
  syscRecord
} from '../../../utils/apis/dataExchange/index'
import { BasicParams } from '../../../utils/basicParams'
import { SalaryParamenters } from '../../../utils/basicSetting/salaryparameters'
import { BillGroup } from '@/utils/basicSetting/billgroup'
export default {
  name: 'Payment', // 成本-薪酬系统
  components: {},
  data() {
    const _this = this
    return {
      expireTimeOptionBm: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() > new Date(_this.$util.currentDate()).getTime()
        }
      },
      tableDataDialog: [],
      newYearMonth: this.$util.currentDate(),
      tableDialog: false,
      formData: {
        yearMonthOld: '',
        ruleCodeOld: '',
        yearMonthNew: '',
        ruleCodeNew: ''
      },
      isShowJc: false,
      isFilterForm: false,
      formInfo: {
        domains: [
          {
            salaryItemCode: '',
            salaryItemName: '',
            costItemCode: '',
            costItemName: ''
          }
        ],
        ruleCode: ''
      },
      ztOptions: [],
      ztList: [],
      gzList: [],
      cbList: [],
      dialogVisible: false,
      title: '',
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      filterElements: [
        {
          clearable: false,
          value: this.$util.currentDate(),
          remote: true,
          remoteMethod: this.unitFilter,
          itemLabel: 'value',
          itemValue: 'value',
          label: '年/月',
          key: 'yearMonth',
          mode: 'month',
          type: 'date-picker',
          format: 'yyyy-MM',
          options: [],
          change: this.hanldeChangeSelect
        },
        {
          clearable: true,
          key: 'ruleCode',
          type: 'Select',
          label: '账套',
          value: '',
          width: 210,
          itemLabel: 'name',
          itemValue: 'acCode',
          filterable: true,
          options: [],
          change: this.hanldeChangeSelectZt
        },
        {
          clearable: true,
          key: 'salaryItemCode',
          type: 'Select',
          label: '工资项目',
          value: '',
          width: 210,
          itemLabel: 'salaItemName',
          itemValue: 'salaItemCode',
          filterable: true,
          options: []
        }
        // {
        //   clearable: true,
        //   key: "rowStatus",
        //   type: "Select",
        //   label: "启用状态",
        //   value: "",
        //   width: 210,
        //   options: [
        //     {
        //       label: "全部",
        //       value: "",
        //     },
        //     {
        //       label: "已启用",
        //       value: "0",
        //     },
        //     {
        //       label: "未启用",
        //       value: "1",
        //     },
        //   ],
        // },
      ],
      total: 0,
      pageSize: 20,
      currentPage: 1,
      tableData: [],
      tableLoading: false,
      newParamList: {},
      currYear: new Date().getFullYear(),
      currMonth: new Date().getMonth() + 1,
      ztOldData: [],
      ztNewData: []
    }
  },
  created() {
    this.getSelect()
    // this.handleremoteMethod();
  },
  methods: {
    handleYMToZt(value) {
      this.handleZt(value, 3)
    },
    handleCheck(value) {
      const fieldVal = this.$refs.filterForm.getParms()
      if (!fieldVal.ruleCode) {
        this.$message.warning('请选择账套1')
        return
      }
      const param = {
        year: fieldVal?.yearMonth.split('-')[0],
        month: fieldVal?.yearMonth.split('-')[1],
        accSet: fieldVal.ruleCode
      }
      this.tableDataDialog = []
      checkRelation(param).then((res) => {
        if (res.data.code == 200) {
          this.tableDialog = true
          this.tableDataDialog = res.data.data
        }
      })
    },
    handleYmOldData(value) {
      this.handleZt(value, 1)
    },
    handleYmNewData(value) {
      this.handleZt(value, 2)
    },
    handleSaveJc() {
      if (!this.formData.yearMonthOld) {
        this.$message.warning('请选择源年份')
        return false
      }
      if (!this.formData.yearMonthNew) {
        this.$message.warning('请选择目标年份')
        return false
      }
      if (!this.formData.ruleCodeOld) {
        this.$message.warning('请选择源账套')
        return false
      }
      if (!this.formData.ruleCodeNew) {
        this.$message.warning('请选择目标账套')
        return false
      }
      const param = {
        yearMonthOld: this.formData.yearMonthOld,
        ruleCodeOld: this.formData.ruleCodeOld,
        yearMonthNew: this.formData.yearMonthNew,
        ruleNameNew: this.filterElements[1].options.find(
          (item) => item.acCode === this.formData.ruleCodeNew
        )?.name,
        ruleCodeNew: this.formData.ruleCodeNew
      }
      inheritzt(param).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.isShowJc = false
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleJc() {
      // 继承
      for (const key in this.formData) {
        this.formData[key] = ''
      }
      this.isShowJc = true
    },
    handleToXg() {
      const fieldVal = this.$refs.filterForm.getParms().yearMonth
      const param = {
        year: fieldVal?.split('-')[0],
        month: fieldVal?.split('-')[1]
      }
      syscRecord(param).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleExport() {
      // 导出
      const fieldVal = this.$refs.filterForm.getParms()
      const param = {
        yearMonth: fieldVal?.yearMonth,
        ruleCode: fieldVal?.ruleCode,
        salaryItemCode: fieldVal?.salaryItemCode,
        rowStatus: fieldVal?.rowStatus
      }
      rdCostsalaryrelationDown(param).then((res) => {
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '成本-薪酬系统.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleClearArray() {
      this.filterElements[2].value = ''
      this.filterElements[2].options = []
    },
    hanldeChangeSelectZt(value) {
      // 账套改变获取工资项目
      if (value) {
        const param = {
          accId: value
        }
        getSalarySource(param).then((res) => {
          if (res.data.code === 200) {
            this.filterElements[2].options = res.data.data
          }
        })
      } else {
        this.$refs.filterForm.handleForceSet({
          salaryItemCode: ''
        })
        this.handleClearArray()
      }
    },
    hanldeChangeSelect(value) {
      this.handleClearArray()
      this.$refs.filterForm.handleForceSet({
        ruleCode: '',
        salaryItemCode: ''
      })
      this.handleZt(value)
    },
    handleChangeZt(value) {
      const param = {
        accId: value
      }
      getSalarySource(param).then((res) => {
        if (res.data.code === 200) {
          this.gzList = res.data.data
        }
      })
    },
    handleZt(value, type) {
      // 账套查询，根据年月输入查询具体
      const billgroup = new BillGroup()
      billgroup.year = value && value.split('-')[0]
      billgroup.month = value && value.split('-')[1]
      getAcSetSource(billgroup).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data
          if (type === 1) {
            this.ztOldData = res.data.data
          } else if (type === 2) {
            this.ztNewData = res.data.data
          } else if (type === 3) {
            this.ztList = res.data.data
          }
        }
      })
    },
    handleremoteMethod() {
      // 账套数据
      const billgroup = new BillGroup()
      billgroup.year = this.currYear
      billgroup.month = this.currMonth

      getAcSetSource(billgroup).then((res) => {
        if (res.data.code === 200) {
          this.ztList = res.data.data
        }
      })
    },
    switchUse(row) {
      const salarys = new SalaryParamenters()
      salarys.id = row.id
      salarys.rowStatus = row.rowStatus
      modifyRdCostSalaryRelation(salarys).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getData(val) {
      const basicParams = new SalaryParamenters()
      basicParams.yearMonth = this.newParamList.yearMonth
      basicParams.ruleCode = this.newParamList.ruleCode
      basicParams.salaryItemCode = this.newParamList.salaryItemCode
      basicParams.rowStatus = this.newParamList.rowStatus
      basicParams.pageIndex = this.pageAttr.currentPage
      basicParams.pageSize = this.pageAttr.pageSize
      this.tableLoading = true
      getRdCostSalaryRelation(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.tableLoading = false
          this.tableData = res.data.data.list
          this.pageAttr.total = res.data.data.total || 0
        }
      })
    },
    handleAddFormItem() {
      // 添加动态表
      this.formInfo.domains.push({
        salaryItemCode: '',
        salaryItemName: '',
        costItemCode: '',
        costItemName: ''
      })
    },
    handleReduceFormItem(index) {
      // 删除动态表
      this.formInfo.domains.splice(index, 1)
    },
    handleEdit(row) {
      this.rowId = row.edId
      this.title = '编辑'
      this.dialogVisible = true
      const basicParams = new SalaryParamenters()
      if (row.edId) {
        getEnumDetailSource(basicParams).then((res) => {
          if (res.data.code == 200) {
            this.formInfo.edExtraFirstCode = res.data.data[0].edExtraFirstCode
            this.formInfo.edExtraSecondCode =
              res.data.data[0].edExtraSecondCode
          }
        })
      } else {
        this.formInfo.edExtraFirstCode = row.edExtraFirstCode
      }
    },
    handleDel(row) {
      // 删除
      const ids = [row.id]
      this.$confirm({
        title: '温馨提示',
        content: '您确定要删除该条数据?',
        okText: '确定',
        cancelText: '取消',
        okFn: () => {
          batchDeleteRdCostSalaryRelation(ids).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.getData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        },
        cancelFn: () => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      })
    },
    handleConfirm() {
      // 确定
      if (!this.formInfo.ruleCode) {
        this.$message.warning('请选择账套')
        return
      }

      const noData = []
      this.formInfo.domains.forEach((item) => {
        if (!item.salaryItemCode || !item.costItemCode) {
          noData.push(item)
        }
      })
      if (noData.length > 0) {
        this.$message.warning('请填写完整数据')
        return
      }
      const arr = this.formInfo.domains.map((item, index) => {
        const recostsalary = new SalaryParamenters()
        recostsalary.id = this.rowId || ''
        recostsalary.ruleCode = this.formInfo.ruleCode
        recostsalary.extendField1 = this.newYearMonth && this.newYearMonth.split('-')[0]
        recostsalary.extendField2 = this.newYearMonth && this.newYearMonth.split('-')[1]
        recostsalary.extendField3 = this.ztList.find(
          (el) => el.acCode == this.formInfo.ruleCode
        ).name
        recostsalary.salaryItemCode = item.salaryItemCode
        recostsalary.salaryItemName = this.gzList.find(
          (el) => el.salaItemCode == item.salaryItemCode
        ).salaItemName
        recostsalary.costItemCode = item.costItemCode
        recostsalary.costItemName = this.cbList.find(
          (el) => el.edCode == item.costItemCode
        ).edName
        recostsalary.year =
          this.newYearMonth && this.newYearMonth.split('-')[0]
        recostsalary.month =
          this.newYearMonth && this.newYearMonth.split('-')[1]
        return recostsalary
      })
      console.info(arr)
      insertBatchRdCostSalaryRelation(arr).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.dialogVisible = false
          // this.getData();
          location.reload()
        } else {
          this.$message.error(res.data.message)
        }
      })

      // recostsalary.id = this.rowId;
      // if (this.rowId) {
      //   ModifyRowStarts(salarys).then((res) => {
      //     if (res.data.code === 200) {
      //       this.$message.success(res.data.message);
      //       // this.getData();
      //       location.reload();
      //       this.showEidtVlidate = false;
      //     } else {
      //       this.$message.error(res.data.message);
      //     }
      //   });
      // } else {
      //   insertBatchRdCostSalaryRelation(arr).then((res) => {
      //     if (res.data.code === 200) {
      //       this.$message.success(res.data.message);
      //       this.dialogVisible = false;
      //       // this.getData();
      //       location.reload();
      //     } else {
      //       this.$message.error(res.data.message);
      //     }
      //   });
      // }
    },
    handleAdd(type) {
      // 新增
      this.formInfo.domains = [
        {
          salaryItemCode: '',
          salaryItemName: '',
          costItemCode: '',
          costItemName: ''
        }
      ]
      this.formInfo.ruleCode = ''
      this.dialogVisible = true
      this.handleZt(this.newYearMonth)
      this.title = '新增'
    },
    getSelect() {
      // 账套
      const basicParams = new SalaryParamenters()
      // getlistYearAndMonth().then((res) => {
      //   if (res.data.code === 200) {
      //     this.isFilterForm = true;
      //     this.filterElements[0].options = res.data.data.data;
      //     this.$nextTick(() => {
      //       this.filterElements[0].value = res.data.data.data[0].value;
      //       this.handleZt(res.data.data.data[0].value);
      //     });
      //   }
      // });
      basicParams.edParentCode = 'CostItem'
      getEnumDetailSource(basicParams).then((res) => {
        if (res.data.code === 200) {
          this.cbList = res.data.data
        }
      })
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData()
    },
    resetForm(data) {
      // 查询
      this.newParamList = data
      this.getData()
    },
    searchSubmit() {}
  }
}
</script>

<style lang="less" scoped>
// .form-box{
//   height: 450px;
//   overflow-y: auto;
// }
.list-item {
  position: relative;
}
.el-icon-circle-plus-outline,
.el-icon-circle-close {
  position: absolute;
  top: 10px;
  right: -20px;
}
.el-icon-circle-plus-outline:hover,
.el-icon-circle-close:hover {
  cursor: pointer;
}
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
.jc-wraper {
  margin: 10px 15px;
  height: calc(100% - 20px);
  overflow-y: auto;
  .jc-item {
    font-size: 12px;
    line-height: 1.7;
  }
}
</style>
